/**
 * 缓存数据优化
 * 当页面引入：
 * var cache = require('utils/cache.js');
 * 
 * 全局注入：
 * import cache from '../cache'
 * Vue.prototype.$cache = cache
 * 
 * 使用方法 【
 *     一、设置缓存
 *         string / boolean    cache.setDatahc('k', 'string你好啊');
 *         json      cache.setJson('k', { "b": "3" }, 2);
 *         array     cache.setJson('k', [1, 2, 3]);
 *     二、读取缓存
 *         string / boolean    cache.getDatahc('k');
 *         json      cache.getJson('k');
 *         array     cache.getJson('k');
 *     三、移除/清理  
 *         移除: cache.remove('k');//常用
 *         清理：cache.clear(); 
 * 】
 * 弹窗 showSuccessToast  showNoneToast showLoadingToast  //全部默认1.5秒时间
 * 还有跳转类型，可参考下面方面。自行修改封装
 * @type {String}
 */
var postfix = '_whx'; // 缓存前缀
/**
 * 设置缓存 
 * @param  {[type]} k [键名]
 * @param  {[type]} v [键值]
 * @param  {[type]} t [时间、单位秒]
 */
function put(k, v, t) {
    uni.setStorageSync(k, v) 
    var seconds = parseInt(t);
    if (seconds > 0) {
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000 + seconds;
        uni.setStorageSync(k + postfix, timestamp + "")
    } else {
        uni.removeStorageSync(k + postfix)
    }
}


/**
 * 获取缓存 
 * @param  {[type]} k   [键名]
 * @param  {[type]} def [获取为空时默认]
 */
function get(k, def) {
    var deadtime = parseInt(uni.getStorageSync(k + postfix)) 
    if (deadtime) {
        if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
            if (def) {
                return def;
            } else {
                return false;
            }
        }
    }
    var res = uni.getStorageSync(k);
    if (res) {
        return res;
    } else {
        if (def == undefined  || def == "") {
            def = false; 
        }
        return def;
    }
}

function removeStorage(k) {
    uni.removeStorageSync(k);
    uni.removeStorageSync(k + postfix);
}

/**
 * 清理所有缓存
 * @return {[type]} [description]
 */
function clear() {
    uni.clearStorageSync();
}

function setJson(key, value) {
    let jsonString = JSON.stringify(value);
    try {
        uni.setStorageSync(key, jsonString);
    } catch (e) {
        // error
    }
}
function setDatahc(key, value) {
    try {
        uni.setStorageSync(key, value);
    } catch (e) {
        // error
    }
}
function getDatahc(key) {
    try {
        const value = uni.getStorageSync(key);
        if (value) {
            return value;
        }else{
            return null
        }
    } catch (e) {
        // error
        return null
    }
}
function getJson(key) {
    try {
        const value = uni.getStorageSync(key);
        if (value) {
            return JSON.parse(value);
        }else{
            return null
        }
    } catch (e) {
        return null
        // error
    }

}
function clearStorage() {
    uni.clearStorage();
}
function insert(param) { //队列插入数据
    param.capacityNum = param.capacityNum || 100; //队列容量 默认队列中超过100条数据，自动删除尾部
    let data = this.getJson(param.key);
    if (data instanceof Array) {
        if (data.length > param.capacityNum) {
            let total = data.length - param.capacityNum;
            for (let i = 0; i < total; i++) {
                data.pop();
            }
        }
        data.unshift(param.value);
    } else {
        data = [];
        data.push(param.value);
    }
    this.setJson(param.key, data);
}
function removeItem(key, itemIds) { //提供itemIds数组 批量删除队列中的某项数据
    let data = this.getJson(key);
    if (data instanceof Array) {
        for (let i = 0; i < itemIds.length; i++) {
            for (let p = 0; p < data.length; p++) {
                if (itemIds[i] === data[p].itemid) {
                    data.splice(p, 1);
                    break;
                }
            }
        }
        this.setJson(key, data);
    }
}
function isExist(key, itemId) { //检测某条数据在队列中是否存在
    let data = this.getJson(key);
    if (data instanceof Array) {
        for (let p = 0; p < data.length; p++) {
            if (itemId === data[p].itemid) {
                return true;
            }
        }
    }
    return false;
}
function remove(key) { //删除某条队列
    try {
        uni.removeStorageSync(key);
        //localStorage.removeItem(key)
    } catch (e) {
        // error
    }
}
function getCount(key) { //获取队列中全部数据数量
    let data = this.getJson(key);
    if (data instanceof Array) {
        return data.length;
    }
    return 0;
}

/**
 * 弹窗
 * @param  {[type]} title [标题]
 */
function showNoneToast(title){
    uni.showToast({
        title: title,
        icon:'none',
        duration:1500
    })
}

/**
 * 失败
 * @param  {[type]} title [标题]
 */
function showfailToast(title){
	//#ifdef MP-WEIXIN
	wx.showToast({
	  title: title,
	  icon: 'error',
	  duration: 1500
	})
	//#endif
	//#ifndef MP-WEIXIN
	uni.showToast({
	    title: title,
	    icon:'none',
	    duration:1500
	})
	//#endif
}

/**
 * 登录弹窗
 * @param  {[type]} title [标题]
 */
function showloginToast(){
	//#ifdef MP
    uni.showToast({
        title: "未登录",
        icon:'none',
        duration:1500
    })
	//#endif
	//#ifndef MP
	uni.navigateTo({
		url:"/pages/login/login"
	})
	//#endif
}

/**
 * 弹窗
 * @param  {[type]} title [标题]
 */
function showLoading(title){
    uni.showLoading({
        title: title,
    })
}
/**
 * 弹窗
 */
function hideLoading(){
    uni.hideLoading()
}

/**
 * 弹窗
 * @param  {[type]} title [标题]
 * @param  {[type]} icon [类型]
 * @param  {[type]} sec [时间、单位秒]
 */
function showToast(title,icon,sec){
    uni.showToast({
        title: title,
        icon:(icon?icon:'none'),
        duration:(sec?sec:"1500")
    })
}

/**
 * 成功弹窗
 * @param  {[type]} title [标题]
 * @param  {[type]} icon [类型]
 * @param  {[type]} sec [时间、单位秒]
 */
function showSuccessToast(title){
    uni.showToast({
        title: title,
        icon:"success",
        duration:1500
    })
}
/**
 * 加载弹窗
 * @param  {[type]} title [标题]
 * @param  {[type]} icon [类型]
 * @param  {[type]} sec [时间、单位秒]
 */
function showLoadingToast(title){
    uni.showToast({
        title: title,
        icon:"loading",
        duration:1500
    })
}
/**
 * 跳转
 * @param  {[type]} pageurl [页面]
 */
function navigateTo(pageurl){
    uni.navigateTo({
      url: pageurl,
    })
}
/**
 * 跳转
 * @param  {[type]} pageurl [页面]
 */
function redirectTo(pageurl){
    uni.redirectTo({
        url: pageurl
    })
}
/**
 * 返回
 */
function navigateBack(){
    uni.navigateBack({})
}

module.exports = {
    put: put,
    get: get,
    removeStorage: removeStorage,
    clear: clear,
    setJson:setJson,
    setDatahc:setDatahc,
    getDatahc:getDatahc,
    getJson:getJson,
    clearStorage:clearStorage,
    insert:insert,
    removeItem:removeItem,
    getCount:getCount,
    showToast:showToast,
	showNoneToast:showNoneToast,
	showfailToast:showfailToast,
	showSuccessToast:showSuccessToast,
	showLoadingToast:showLoadingToast,
	showLoading:showLoading,
	hideLoading:hideLoading,
	showloginToast:showloginToast,
    navigateTo:navigateTo,
    navigateBack:navigateBack,
    redirectTo:redirectTo,
}